from ...validator import validators
from ... import processor as proc
from ... import hal
from ... import halext
from ..base import BaseController


class RankOfryCardController(BaseController):
    """排行榜/ranks

    @see also `controllers.py:RankController`
    """
    validator = validators.RankValidator
    processor = proc.RankOfryCardProcessorObj
    document = halext.RankOfryCardSchema
    collection = halext.RankOfryCardCollection

    columns = (
        'id',
        'leagueid',
        'clubid',
        'userid',
        'score',
        'ext',
        'type',
        'lastupdated',
    )

    def dictify(self, columns):
        return {key: columns[i] for i, key in enumerate(self.columns)}

    def c(self, collection):
        """Depends - database's table structure
        """
        size = len(self.columns)

        def split(collection):
            results = []
            for row in collection:
                red = self.dictify(row[:size])
                yellow = self.dictify(row[size:size*2])
                rank = row[size*2]
                if red['id'] is None:
                    red, yellow = yellow, red
                    yellow['score'] = red['score']
                red['score'] = red['score'] if red['score'] is not None else 0
                yellow['score'] = yellow['score'] if yellow['score'] is not None else 0
                results.append({'Red': red, 'Yellow': yellow, 'rank': rank})
            return results

        return {'ranks': split(collection)}
